package alkaid.eis.schedule.domain;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.CreationTimestamp;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import alkaid.eis.common.util.SnowflakeHelper;
import alkaid.eis.common.util.StringHelper;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * 任务日志
 *  
 * @author Lucky Yang
 * @since 0.0.1
 */
@Setter
@Getter
@ToString
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Entity
@Table(name = "eis_schedule_job_log")
@EntityListeners({AuditingEntityListener.class})
public class JobLog {
    public static enum Level {
        /** 已启动*/
        STARTED,
        /** 运行 */
        RUNNING,
        /** 错误 */
        ERROR,
        /** 完成 */
        COMPLETE,
        /** 已停止 */
        STOPPED;
    }
    
    @Id
    @EqualsAndHashCode.Include
    @Column(updatable = false, nullable = false, unique = true)
    private Long id;

    
    @CreationTimestamp
    @Column(updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date createTime;

    @ManyToOne
    @JoinColumn(name = "jobInfoId")
    private JobInfo jobInfo;

    /** 信息等级 */
    @Enumerated(EnumType.STRING)
    private Level level;

    /** 消息 */
    private String message;

    /** 耗时：毫秒 */
    private Long costTime;

    public JobLog() {
    }

    public JobLog(JobInfo jobInfo, Level level, String message) {
        this.jobInfo = jobInfo;
        this.level = level;
        if(message != null) {
            // 500个字符
            this.message = StringHelper.limitLength(message, 999);
        }
    }
 
    public JobLog(JobInfo jobInfo, Level level, String message, Long costTime) {
        this(jobInfo, level, message);
        this.costTime = costTime;
    }

    @PrePersist
    public void preAction() {
        if (id == null) {
            id = SnowflakeHelper.INSTANCE.nextId();
        }

    }
}
